﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Telerik.Cms.Web;
using Telerik.Framework.Web.Design;

namespace SitefinityWatch.Web.UI
{
    [DefaultProperty("Columns")]
    [ControlDesigner("SitefinityWatch.Web.UI.Design.SubLinkDesigner")]
    public class SubLinks : System.Web.UI.WebControls.CompositeControl
    {
        protected override void CreateChildControls()
        {
            // If using embedded stylesheets, then include embedded style in <head>
            if (UseEmbeddedStyles)
                EmbedStyles();

            SiteMapNode startNode = GetStartingNode();
            if (startNode.ChildNodes.Count > 0)
            {
                // Use the Columns property to determine the number of items per column.
                decimal itemsInColumn = Math.Ceiling((decimal)startNode.ChildNodes.Count / (decimal)Columns);
                int itemCount = 0;
                this.Controls.Add(new LiteralControl("<div class=\"" + CssClass + "\">"));
                this.Controls.Add(new LiteralControl("<ul>"));
                foreach (CmsSiteMapNode node in startNode.ChildNodes)
                {
                    itemCount++;
                    if (itemCount > itemsInColumn)
                    {
                        itemCount = 1;
                        itemsInColumn = Math.Round((decimal)startNode.ChildNodes.Count / (decimal)Columns);
                        this.Controls.Add(new LiteralControl("</ul>"));
                        this.Controls.Add(new LiteralControl("<ul>"));
                    }

                    this.Controls.Add(new LiteralControl("<li>"));
                    this.Controls.Add(CreateHyperlink(node));
                    this.Controls.Add(new LiteralControl("</li>"));
                }
                this.Controls.Add(new LiteralControl("</ul>"));
                this.Controls.Add(new LiteralControl("</div>"));
            }
        }

        /// <summary>
        /// Handles adding a stylesheet reference to the page's <head> tag
        /// </summary>
        private void EmbedStyles()
        {
            // Getting my own reference to System.Web.UI.Page to ensure it exists.
            // Using this.Page instead will result in a null object in the Sitefinity Page Editor.
            var page = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;
            HtmlLink link = new HtmlLink();
            link.Href = page.ClientScript.GetWebResourceUrl(this.GetType(), "SitefinityWatch.Web.UI.Resources.sitefinitywatch.css");
            link.Attributes.Add("type", "text/css");
            link.Attributes.Add("rel", "stylesheet");
            page.Header.Controls.Add(link);
        }

        /// <summary>
        /// Finds the "starting" node that will be used to find child links.
        /// </summary>
        private SiteMapNode GetStartingNode()
        {
            if (StartNodeMode == StartNodeModes.SelectedPageId)
            {
                if (PageId == Guid.Empty)
                {
                    return SiteMap.RootNode;
                }
                else
                {
                    CmsSiteMapProvider cmsMap = (CmsSiteMapProvider)SiteMap.Provider;
                    return cmsMap.FindSiteMapNodeFromKey(PageId.ToString());
                }
            }
            else
            {
                return SiteMap.CurrentNode;
            }
        }

        /// <summary>
        /// Creates a Hyperlink to a sub linked page.
        /// </summary>
        private HyperLink CreateHyperlink(CmsSiteMapNode node)
        {
            var hyperLink = new HyperLink();
            hyperLink.Text = node.Title;
            hyperLink.NavigateUrl = node.Url;

            if (ShowTooltips)
                hyperLink.ToolTip = node.CmsPage.Title;

            return hyperLink;
        }

        [Category("Main")]
        [DefaultValue(1)]
        [Description("The number of columns to display sub-links into.")]
        public int Columns
        {
            get
            {
                if (_columns <= 0)
                    return 1;
                else
                    return _columns;
            }
            set
            {
                _columns = value;
            }
        }

        [Category("Main")]
        [DefaultValue(true)]
        [Description("Should detailed tooltips be displayed when hovering over sub-links.")]
        public bool ShowTooltips { get; set; }

        [Category("Appearance")]
        public bool UseEmbeddedStyles
        {
            get
            {
                return _useembeddedstyles;
            }
            set
            {
                _useembeddedstyles = value;
            }
        }

        [Category("Appearance")]
        public override string CssClass
        {
            get
            {
                return _cssClass;
            }
            set
            {
                _cssClass = value;
            }
        }

        [Category("Main")]
        public StartNodeModes StartNodeMode
        {
            get
            {
                return _StartNodeMode;
            }
            set
            {
                _StartNodeMode = value;
            }
        }

        [Telerik.Cms.Web.UI.WebEditor("SitefinityWatch.Web.UI.Editors.PageIdSelector, SitefinityWatch.Web.UI")]
        [Category("Main")]
        public Guid PageId { get; set; }

        public enum StartNodeModes { CurrentPage, SelectedPageId }

        private int _columns = 1;
        private string _cssClass = "sitefinitywatch_sublinks";
        private bool _useembeddedstyles = true;
        private StartNodeModes _StartNodeMode;
    }
}